package com.vertx.db;

import com.vertx.util.Runner;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.pgclient.PgConnectOptions;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.*;

public class FuturePostgresVerticle extends AbstractVerticle {

	PgPool pool = null;

	public static void main(String[] args) {

		Runner.runExample(FuturePostgresVerticle.class);

	}

	@Override
	public void start(Promise<Void> startPromise) throws Exception {
		PgConnectOptions connectOptions = new PgConnectOptions()
				.setPort(5432)
				.setHost("localhost")
				.setDatabase("postgres")
				.setUser("walter")
				.setPassword("walter123");
		// Pool options
		PoolOptions poolOptions = new PoolOptions().setMaxSize(5);

		// Create the pooled client
		pool = PgPool.pool(vertx, connectOptions, poolOptions);

		// Get a connection from the pool
		this.getCon().compose(con -> this.getRows(con))
				.onSuccess(rows -> {
					rows.forEach(item -> {
							System.out.println("id : " + item.getInteger(0) + ", first name: " +
									item.getString(1) + ", second name: " + item.getString(2));
						}
					);
				});

	}

	/*
	 1. 找到handler的泛型对象，用Future包装作为方法返回值
	 2. 创建Promise
	 3. 搬代码，并把结果放到promise.complete
	 4. promise.future();
	 */
	private Future<SqlConnection> getCon() {
		//固定写法
		Promise<SqlConnection> promise = Promise.promise();
		pool.getConnection(con -> {
			if (con.succeeded()) {
				SqlConnection sqlConnection = con.result();
				promise.complete(sqlConnection);
			} else {
				System.out.println("fail : " + con.cause().getMessage());
			}
		});
		return promise.future();
	}

	private Future<RowSet<Row>> getRows(SqlConnection sqlConnection) {
		//固定写法
		Promise<RowSet<Row>> promise = Promise.promise();
		sqlConnection.preparedQuery("select * from t_person")
				.execute(rs -> {
					sqlConnection.close();
					//第三步 加工查询出来的数据 并返回给客户端
					if (rs.succeeded()) {
						promise.complete(rs.result());
					} else {
						System.out.println("fail : " + rs.cause().getMessage());
					}
				});
		return promise.future();
	}
}
